package servlet;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class EncodeFilter implements Filter{
    private String _encoding;
    protected HttpServletRequest _request;
    protected HttpServletResponse _response;
   
    /**
     * 初始化 
     */
    public void init(FilterConfig config) throws ServletException {
        this._request   = null;
        this._response  = null;
        this._encoding  = config.getInitParameter("charset");
    }
    
    /**
     * 进行过滤 
     */
    public void doFilter(ServletRequest request,
                           ServletResponse response,
                           FilterChain filterChain) throws IOException, ServletException{ 
        this._request   = (HttpServletRequest) request;
        this._response  = (HttpServletResponse) response;
        this._request.setCharacterEncoding(this._encoding);
        this._response.setCharacterEncoding(this._encoding);
        filterChain.doFilter(this._request, this._response);
    }
    
    /**
     * 销毁对象 
     */
    public void destroy() {
        this._request   = null;
        this._response  = null;
    }
   
} 
